package com.skycode7.Servlet;

import com.skycode7.bean.NewsBean;
import com.skycode7.dao.NewsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/newsfront.html")
public class NewFrontServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");//请求参数类型的设置
        String sp = req.getParameter("page");//前端的参数都是String类型
        int page = 1;
        if (sp != null && !sp.equals("")) {//传了情况下
            page = Integer.parseInt(sp);//将前端字符数字强制化为整形
        }
        NewsDao newsDao = new NewsDao();
        List<NewsBean> list = newsDao.getList(page);//分页查询
        int totaCunt = newsDao.count();
        int totaPage;
        if (totaCunt%10==0){
            totaPage = totaCunt/10;
        }else {
            totaPage = totaCunt/10+1;
        }
        int upPage;
        if (page ==1){
            upPage =1;
        }else {
            upPage = page-1;
        }
        int downPage;
        if (page == totaPage){
            downPage = totaPage;
        }else {
            downPage = page+1;
        }
        req.setAttribute("curPage",page);
        req.setAttribute("upPage",upPage);
        req.setAttribute("downPage",downPage);
        req.setAttribute("totalCount",totaCunt);
        req.setAttribute("totalPage", totaPage);
        req.setAttribute("list",list);//通过req将list数递给前端
        //属于额外知识
        //getRequestDispatcher决定webapp目录下那个文件显示
        req.getRequestDispatcher("newsFrontList.jsp").forward(req,resp);
    }
}
